package tools.week03;

import io.netty.buffer.Unpooled;
import io.netty.buffer.UnpooledDirectByteBuf;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.*;
import io.netty.util.ReferenceCountUtil;

import static io.netty.handler.codec.rtsp.RtspHeaderValues.KEEP_ALIVE;
import static org.apache.http.HttpHeaders.CONNECTION;

public class MyHttpHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            FullHttpRequest f = (FullHttpRequest) msg;

            String uri = f.uri();

            if(uri.contains("/test")){
                handle(f, ctx, "Hello, Test!");
            }else{
                handle(f, ctx, "Hello, others!");
            }


        }catch (Exception e){
            e.printStackTrace();
        }finally {
            ReferenceCountUtil.release(msg);
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }


    private void handle(FullHttpRequest request, ChannelHandlerContext ctx, String body){
        FullHttpResponse response = null;

        try{
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, Unpooled.wrappedBuffer(body.getBytes()));
            response.headers().set("Content-Type","application/json");
            response.headers().setInt("Content-Length", response.content().readableBytes());
        }catch (Exception e){
            e.printStackTrace();
            response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT);
        }finally {
            if(request!=null){
                if(HttpUtil.isKeepAlive(request)){
                    response.headers().set(CONNECTION, KEEP_ALIVE);
                    ctx.write(response);
                }else{
                    ctx.write(response).addListener(ChannelFutureListener.CLOSE);
                }

            }
        }
    }
}
